//
//  GTCommentViewController.m
//  GiftTalk
//
//  Created by Wan on 16/4/6.
//  Copyright © 2016年 Wan. All rights reserved.
//

#import "GTCommentViewController.h"
#import "GTNetWorkManager.h"
#import "GTGiftCommentCell.h"
#import "GTGiftComment.h"
#import <MJRefresh.h>
#import <MJExtension.h>

@interface GTCommentViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;
@property (weak, nonatomic) IBOutlet UITextField *commentTextField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputContainerViewBottomConstraint;

- (IBAction)sendButton:(UIButton *)sender;

/****************** 辅助属性 **********************/
/** 评论数据 */
@property (strong, nonatomic) NSMutableArray *comments;
/** 获取下一页 url */
@property (strong, nonatomic) NSString *nextPageUrlStr;

@end

static NSString * const commentIdentifier = @"commentCell";

@implementation GTCommentViewController

- (NSMutableArray *)comments
{
    if (!_comments) {
        _comments = [NSMutableArray array];
    }
    return _comments;
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setupNav];
    
    [self setupTableView];
    
    [self setupRefresh];
}

- (void)setupNav {
    self.navigationItem.title = @"评论";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textfieldTextChange) name:UITextFieldTextDidChangeNotification object:self.commentTextField];
}

- (void)setupTableView {
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([GTGiftCommentCell class]) bundle:nil] forCellReuseIdentifier:commentIdentifier];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (void)setupRefresh {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置行高
    self.tableView.estimatedRowHeight = 80;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer.hidden = YES;
}

- (void)checkFooterState {
    if (self.nextPageUrlStr == nil) {
        self.tableView.mj_footer.hidden = YES;
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - 加载数据
- (void)loadNewData {
    NSString *firstPageURLString = @"v2/posts/1001837/comments?limit=20&offset=0";
    
    [[GTNetWorkManager shareNetWorkTool] GET:firstPageURLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.comments = [GTGiftComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"comments"]];
        NSString *nextURLString = responseObject[@"data"][@"paging"][@"next_url"];
        if ([nextURLString isKindOfClass:[NSNull class]] || [self.nextPageUrlStr isEqualToString:nextURLString]) {
            // 如果nextURLString是值为空的对象，就将self.nextPageURLString赋值为空对象
            // 注意nil和Null对象的区别，一个是空对象，一个是值为空的对象
            self.nextPageUrlStr = nil;
        } else {
            self.nextPageUrlStr = nextURLString;
        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        GTLog(@"%@",error);
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData {
    [[GTNetWorkManager shareNetWorkTool] GET:self.nextPageUrlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableArray *comments = [GTGiftComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"comments"]];
        [self.comments addObjectsFromArray:comments];
        NSString *nextURLString = responseObject[@"data"][@"paging"][@"next_url"];
        if ([nextURLString isKindOfClass:[NSNull class]] || [self.nextPageUrlStr isEqualToString:nextURLString]) {
            // 如果nextURLString是值为空的对象，就将self.nextPageURLString赋值为空对象
            // 注意nil和Null对象的区别，一个是空对象，一个是值为空的对象
            self.nextPageUrlStr = nil;
        } else {
            self.nextPageUrlStr = nextURLString;
        }
        
        [self.tableView reloadData];
        [self checkFooterState];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        GTLog(@"%@",error);
        [self checkFooterState];
    }];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.comments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GTGiftCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:commentIdentifier];
    cell.comment = self.comments[indexPath.row];
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GTGiftComment *comment = self.comments[indexPath.row];
    self.commentTextField.placeholder = [NSString stringWithFormat:@"回复 %@",comment.nickname];
    self.commentTextField.text = @"";
    self.sendButton.selected = self.commentTextField.hasText;
    [self.commentTextField becomeFirstResponder];
    
    [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    self.commentTextField.placeholder = @"我也说几句...";
}

#pragma mark - 通知回调
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    
    // 获取键盘基本信息（动画时长与键盘高度）
    NSDictionary *userInfo = [notification userInfo];
    CGRect rect = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    
    CGFloat keyboardHeight = CGRectGetHeight(rect);
    CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 修改下边距约束
    [UIView animateWithDuration:keyboardDuration animations:^{
        self.inputContainerViewBottomConstraint.constant = -keyboardHeight;
    }];
    
    [self.view layoutIfNeeded];
    
    /*
    CGRect keyboardFrame = [notification.userInfo[@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue];
    
    self.inputContainerViewBottomConstraint.constant = keyboardFrame.size.height;
     */
}

- (void)textfieldTextChange {
    self.sendButton.selected = self.commentTextField.hasText;
}

#pragma mark - 发送按钮点击事件
- (IBAction)sendButton:(UIButton *)sender {
    GTLog(@"发送评论！");
}

- (void)dealloc {
    [[GTNetWorkManager shareNetWorkTool].operationQueue cancelAllOperations];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
